package com.easyOrder.service.impl.push;

/**
 * Created by liutao on 2017/7/21.
 */

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.easyOrder.core.mongo.log.LogComponent;
import com.easyOrder.core.push.PushMessage;
import com.easyOrder.core.push.PushResult;
import com.easyOrder.service.enums.MessageChannel;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.MessageFormat;
import java.util.List;


public class JPushChannel implements IMessagePushChannel {

    private List<JPushClient> jpushClients;

    private Logger logger = Logger.getLogger(JPushChannel.class);

    public void setJpushClients(List<JPushClient> jpushClients) {
        this.jpushClients = jpushClients;
    }

    @Autowired
    LogComponent logComponent;

    @Override
    public PushResult push(PushMessage message) {
        PushResult result = new PushResult();
        result.setChannel(getChannelName().getDesc());
        if (StringUtils.isBlank(message.getAlias())) {
            result.setResponse("Not push with blank message tag");
            result.setPushSuccess(false);
            logComponent.insertPushMessage(message,result);
            return result;
        }
        try {
            PushPayload payload = buildPayLoad(message);
            for (JPushClient jpushClient : jpushClients) {
                cn.jpush.api.push.PushResult pushResult = jpushClient.sendPush(payload);
                result.setResponse(pushResult.getOriginalContent());
                if (logger.isDebugEnabled()) {
                    logger.debug(MessageFormat.format("Push {0} to {1} get result {2} - {3}", message.getContent(),
                            message.getTag(), result));
                }
            }
            result.setPushSuccess(true);
        } catch (APIConnectionException | APIRequestException e) {
            logger.error(e, e);
            result.setPushSuccess(false);
        }
        logComponent.insertPushMessage(message,result);
        return result;
    }

    private PushPayload buildPayLoad(PushMessage message) {

        Notification notification = buildNotification(message);

        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(message.getAlias()))
                .setNotification(notification)
                .build();
        return payload;
    }

    private Notification buildNotification(PushMessage message) {
        Notification notification = Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(message.getContent())
                        .addExtras(message.getExtras())
                        .incrBadge(1)
                        .build())
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(message.getContent())
                        .addExtras(message.getExtras())
                        .build())
                .build();
        return notification;
    }

    @Override
    public MessageChannel getChannelName() {
        return MessageChannel.JPush;
    }
}
